package com.neusoft.neuiotms.dcam.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.mom.messaging.ProducerService;
import com.neusoft.bizcore.web.bean.LogBean;
import com.neusoft.bizcore.web.utils.JsonUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CreateLogMessage {

    @Autowired
    private Environment environment;

    @Autowired
    private ProducerService producerService;

    public void sendMsgToLogServer(final String logBeanJson) {
        final String kafka = this.environment.getProperty("spring.kafka.bootstrap-servers");
        CreateLogMessage.log.info("kakfa地址： " + kafka);

        if (StringUtils.isNotEmpty(kafka)) {
            final String topic = this.environment.getProperty("support.log.kafka-topic");
            CreateLogMessage.log.info("topic名称： " + topic);

            this.producerService.send(topic, logBeanJson);
        }
        CreateLogMessage.log.info("发送的消息内容是： " + logBeanJson);
    }

    public void sendMsgToLogServer(UserBean user, HttpServletRequest request, String operation, String extra) {
        try {
            final LogBean bean = new LogBean();
            bean.setTime(new Date());
            bean.setOperation(operation);
            bean.setExtra(extra);
            if (null != user) {
                bean.setAccount(user.getUsername());
                bean.setUsername(user.getName());
            }
            if (null != request) {
                bean.setIp(this.getRemoteIp(request));
            }

            this.sendMsgToLogServer(JsonUtils.pojoToJson(bean));
        } catch (final Exception e) {
            CreateLogMessage.log.error("", e);
        }
    }

    private String getRemoteIp(final HttpServletRequest request) {
        if (null == request.getHeader("x-forwarded-for")) {
            return request.getRemoteAddr();
        } else {
            return request.getHeader("x-forwarded-for");
        }
    }

}
